﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TheHeGeoDao;
using TheHeGeoDataProcess;
using TheHeGeoServer.Dao;
using TheHeGeoServer.Util;
using SocketClient;

namespace TheHeGeoServer
{
    public partial class PostData : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
               // isConnected = SocketClient.SocketClient.ConnectServer();
                var rq = Request.QueryString["d"];
                if (rq != null)
                {
                    string fileName = "//" + DateTime.Now.ToString("dd-MM-yyyy") + "_log.csv";
                    WriteLog(rq + "," + DateTime.Now.ToString("dd-MM-yy hh:mm:ss:ff"), fileName);
                    ProcessData(rq);
                }
            }
        }
        private void WriteLog(string strLog,string logFile)
        {
            try
            {
                string newPath = Server.MapPath("Log");
                if (!Directory.Exists(newPath))
                {
                    Directory.CreateDirectory(newPath);
                }
                var pathFile = newPath + logFile;
               
                    using (StreamWriter sw = File.AppendText(pathFile)) 
                    {
                        sw.WriteLine(strLog);
                       
                    } 
            }
            catch (Exception)
            {

            }
        }
        protected void ProcessData(string rq)
        {
            try
            {
                string rsUrl = "";
                int syncTime = 0;
                var eq = DataProcess.DataFromStr(rq);
                if (eq == null)
                {
                    WriteLog(rq + "," + DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss:ff") + ",Can not mapping", "//mappingErr.csv");
                }
                else if (eq.IsCorrect)
                {
                    if (EquipmentDao.InsertNewData(eq))
                    {
                        try
                        {

                            var ucmd = UpdateClientCmd(eq);
                            if (ucmd.Contains("ER9"))
                            {
                                rsUrl = "01:" + rsUrl + ucmd;
                            }
                            else
                            {

                                {
                                    if (string.IsNullOrEmpty(ucmd))
                                    {
                                        rsUrl += "01:GOOD";
                                    }
                                    else
                                    {
                                        rsUrl += ucmd;
                                        rsUrl += GetCheckSum();
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            rsUrl += "01:ER90";
                            eq.ErrStr = ex.InnerException==null?
                                (ex.Message + Environment.NewLine + ex.StackTrace):
                                (ex.InnerException.Message + Environment.NewLine + ex.InnerException.StackTrace);
                            EquipmentDao.InsertRaw(eq);
                        }
                    }
                    else
                    {
                        rsUrl += "01:ER91"; //ServerErr

                        EquipmentDao.InsertRaw(eq);
                        WriteLog(eq.RawData + "," +DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss:ff")+ ",ER91", "//ErrLog.csv");
                    }
                    //if (!rsUrl.Contains("ER") && !rsUrl.Contains("GOOD"))
                    //    rsUrl = noOfCmd.ToString("00") + rsUrl;                     
                    ResponseToClient(rsUrl,eq);
                }
                else
                {
                    WriteLog(eq.RawData + "," + DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss:ff") + "," + eq.ErrCode, "//ErrLog.csv");
                    EquipmentDao.InsertRaw(eq);
                    if (!ShouldSendCmd(eq))
                    {
                        switch (eq.ErrCode)
                        {
                            case "00": //Invalid Format
                                ResponseToClient("01:ER" + eq.ErrCode, eq);
                                break;
                            case "02": //Invalid DateTime
                                ResponseSynTime(eq);
                                break;
                        }
                    }
                    else
                    {
                        ResponseToClient(eq.Cmd,eq);
                    }
                }

            }
            catch (ThreadAbortException)
            {
                //WriteLog("DataProcess exception," + rq +","+ DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss:ff"), "//dataprocess.csv");
            }
            catch (Exception ex)
            {
                string strErr = ex.InnerException == null
                    ? (ex.Message + Environment.NewLine + ex.StackTrace)
                    : (ex.InnerException.Message + Environment.NewLine + ex.InnerException.StackTrace);
                WriteLog(strErr + "," + DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss:ff") + ",ER92", "//ErrLog.csv");
                EquipmentDao.InsertRaw(strErr,"ER92");
                ResponseToClient("01:ER92",null);

            }
        }

        protected bool ShouldSendCmd(EquipmentData eq)
        {

            
            //var ent = DaoHelper.ReOpen();
            //var tbs = (from t in ent.ThietBis where (t.MaThietBi == eq.DeviceId && t.Status == 0) select t).ToList();
            var dt = EquipmentDao.SelectThietBi(eq.DeviceId);
            if (dt!=null && dt.Rows.Count>0)
            {
                var tb = dt.Rows[0];
                string str = tb["Cmd"].ToString();
                eq.Cmd = str;
                if (!string.IsNullOrEmpty(eq.Cmd))
                {
                    EquipmentDao.ShouldSendCmd(eq.DeviceId);
                    return true;
                }
            }
            return false;
        }

        protected string UpdateClientCmd(EquipmentData eq)
        {
            string rsUrl=string.Empty;
            string syncT = string.Empty;
            int numbCmd = 0;
            var dt = EquipmentDao.SelectThietBi(eq.DeviceId);
            if (dt!=null && dt.Rows.Count>0)
            {
                if (eq.ErrCode == "9999")
                {
                    syncT = "01:SYNT" + DateTime.Now.ToString("yyMMddHHmmss");
                    //numbCmd++;
                    return syncT;

                }
                var tb = dt.Rows[0];
                string str = tb["Cmd"].ToString();
                eq.Cmd = str;
                
                if (!string.IsNullOrEmpty(eq.Cmd))
                {
                    EquipmentDao.ShouldSendCmd(eq.DeviceId);
                    numbCmd++;
                    //return str;
                }

                if (tb["NeedUpdate"].ToString()=="True")
                {
                    EquipmentDao.SetNeedUpdate(eq.DeviceId);
                    var DSTI = "DSTI" + Convert.ToDouble(tb["TgLayMau"]).ToString("000000.00").Replace(".", "");
                    var DSTL = "DSTL" + Convert.ToDouble(tb["TgLuuTheNho"]).ToString("00000.00").Replace(".", "");
                    numbCmd += 2;
                   // rsUrl += "DSTI" + tb.TgLayMau.ToString("000000.0").Replace(".", "") + tb.TgLuuTheNho.ToString("00000");
                    //rsUrl += "DSTI" + Convert.ToDouble(tb["TgLayMau"]).ToString("000000.0").Replace(".", "") + Convert.ToDouble(tb["TgLuuTheNho"]).ToString("00000");
                    rsUrl = numbCmd.ToString("00") + ":" + DSTI + "," + DSTL + "," + str;
                    rsUrl = rsUrl.TrimEnd(',');
                }

                    
                EquipmentDao.SetLastUpdate(eq.DeviceId);
            }
            else
            {
                rsUrl += "ER93";
                eq.ErrStr = "ER93";
                eq.ErrStr = "Thiet bi ko ton tai hoac da chuyen sang du an khac";

                WriteLog(eq.RawData + "," + DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss:ff") + ",ER93", "//ErrLog.csv");
                EquipmentDao.InsertRaw(eq);
            }
            return rsUrl;
        }

        protected string GetCheckSum()
        {
            //return "ff";
            return "";
        }

        protected void ResponseSynTime(EquipmentData eq)
        {
            var date = DateTime.Now;
            // Session[SessionConst.SES_LAST_SYN_DATE] = date;
            //ResponseToClient( "01SYNT" + date.ToString("yyMMddHHmmss") + GetCheckSum(),eq);
            ResponseToClient("01:SYNT" + date.ToString("yyMMddHHmmss") + GetCheckSum(), eq);
  
        }

        protected void ResponseToClient(string str,EquipmentData eq)
        {
            try
            {
                var sendcmd=eq==null||string.IsNullOrEmpty(eq.Cmd)? ("CMD" + str):(eq.Cmd);
                Response.Charset = "";
                Response.AddHeader("Content-Type","");
                Response.AppendHeader("X-SourceFiles","");
                Response.AppendHeader("Content-Length","");
                Response.AppendHeader("Date","");
                Response.Write(sendcmd);
                Response.End();
            }
            catch (Exception ex)
            {
                //WriteLog("Response to Client", "//ErrLog.txt");
                Console.WriteLine(ex.ToString());
            }
        }

        protected string ResponseSynTimeStr()
        {
            var date = DateTime.Now;
           // Session[SessionConst.SES_LAST_SYN_DATE] = date;
            return "SYNT"+date.ToString("yyMMddHHmmss") + GetCheckSum();
        }

        protected void InvokeNewData(string maThietBi)
        {
//            try
//            {
//                var tb = DaoHelper.Entities.ThietBis.AsEnumerable().FirstOrDefault(p => p.MaThietBi.Equals(maThietBi));
//                if (tb == null) return;
//
//                WebRequest request = WebRequest.Create(Properties.Settings.Default.InvokeNewDataUrl + "_" + tb.UserName);
//                // Set the Method property of the request to POST.
//                request.Method = "POST";
//                // Create POST data and convert it to a byte array.
//                string postData = "This is a test that posts this string to a Web server.";
//                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
//                // Set the ContentType property of the WebRequest.
//                request.ContentType = "application/x-www-form-urlencoded";
//                // Set the ContentLength property of the WebRequest.
//                request.ContentLength = byteArray.Length;
//                // Get the request stream.
//                Stream dataStream = request.GetRequestStream();
//                // Write the data to the request stream.
//                dataStream.Write(byteArray, 0, byteArray.Length);
//                // Close the Stream object.
//                dataStream.Close();
//                // Get the response.
//                WebResponse response = request.GetResponse();
//                // Display the status.
//                Console.WriteLine(((HttpWebResponse) response).StatusDescription);
//                // Get the stream containing content returned by the server.
//                dataStream = response.GetResponseStream();
//                // Open the stream using a StreamReader for easy access.
//                if (dataStream != null)
//                {
//                    var reader = new StreamReader(dataStream);
//                    // Read the content.
//                    string responseFromServer = reader.ReadToEnd();
//                    // Display the content.
//                    Console.WriteLine(responseFromServer);
//                    // Clean up the streams.
//                    reader.Close();
//                }
//                if (dataStream != null) dataStream.Close();
//                response.Close();
//            }
//            catch (Exception)
//            {
//            }
        }

    }
}